package com.example.a2209_shop.login

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.a2209_shop.R
import com.example.a2209_shop.database.DataBaseUtils
import com.example.a2209_shop.databinding.ActivityLoginBinding
import com.example.base.mvvm.BaseActivity
@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {
    /*  lateinit var etName:EditText//延迟初始化
    val etPwd:EditText by lazy {
        findViewById(R.id.et_pwd)
    }
    val viewmodel = LoginViewModel()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        etName = findViewById(R.id.et_name)
        val btnLogin = findViewById<Button>(R.id.btn_login)

        btnLogin.setOnClickListener {
            viewmodel.login(etName.text.toString(),etPwd.text.toString())
        }
        viewmodel.loginSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
    }*/
    @Autowired
    @JvmField
    var username = ""
    @Autowired
    @JvmField
    var password = ""


    override fun initData() {
        viewModel.loginSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                SPUtils.getInstance().put("token",it.data.token)
                SPUtils.getInstance().put("id",it.data.id)
                DataBaseUtils.getDb().getUserDao().insertUser(it.data)//使用Room数据库保存数据
                ARouter.getInstance().build("/app/MainActivity").navigation()
            }
        }
        viewModel.loginFail.observe(this){
            ToastUtils.showLong(it)
        }
    }

    override fun initView() {
        ARouter.getInstance().inject(this)

        binding.etName.setText(username)
        binding.etPwd.setText(password)
        binding.btnLogin.setOnClickListener {
            viewModel.login(binding.etName.text.toString(),binding.etPwd.text.toString())
        }
        //跳转到注册界面
        binding.goReg.setOnClickListener {
            ARouter.getInstance().build("/app/RegisterActivity").navigation()
        }

    }

    override fun getViewModel(): Class<LoginViewModel> {
        return LoginViewModel::class.java
    }

    override fun getLayout() = R.layout.activity_login
}